<template>
    <div class="big">
        <div class="listbox" ref="listbox">
            <div class="list" v-if="shopLists.length!=0">
                <div data-type="0" class="listchild" v-for="(item,index) in shopLists" :key="index" @click.stop="toNext('categoryDetail',{cateNo: item.productNo})">
                    <div class="imgshou" @touchend.capture="touchEnd" @touchstart.capture="touchStart">
                        <p ref="checkbox"> <input type="checkbox" :id="index" class="regular-checkbox" v-model="item.selectbox" @click="change(item,true)" />
                            <label :for="index"></label>
                        </p>
                        <img :src="item.picUrl" alt="">
                        <div class="conts">
                            <p>{{item.productName}}</p>
                            <p>
                                <span>{{item.salePrice}}元</span>
                                <span ref="number">
                                    <x-number v-model="item.buyNumber" :min="1" @on-change="change(item)" class="xnumber" width="30px" ref="xnumber" :fillable=true :max="50"></x-number>
                                </span>
                            </p>
                            <p class="guige">
                                <span v-for="(itemchild,indexchild) in item.specList" :key="indexchild">{{itemchild.specName}}</span>
                            </p>
                        </div>
                    </div>
                    <div class="delte" @click="deleteItem($event,index,item)">删除</div>
                </div>
            </div>
            <show-bg-img :isShow="showBg" title="暂无商品，去看看别的吧~~"></show-bg-img>
        </div>
        <diV class="shopfoot">
            <div class="confoot">
                <div class="left">
                    <div class="one">
                        <p class="check"><input type="checkbox" id="indexcheck" class="regular-checkbox" v-model="checkall" />
                            <label for="indexcheck"></label>
                        </p>
                        <p>全部</p>
                    </div>
                    <div class="two">合计：￥{{shopprice}}</div>
                </div>
                <div class="button" @click="settlement()">结算</div>
            </div>
        </diV>
        <div class="cont"></div>
    </div>
</template>
<script>
// 1实物 2彩票 3券
// payMethod
// 1-RMB
// 2-积分
// 3-RMB+积分
import { XNumber } from "vux";
import { MessageBox, Toast } from "mint-ui";
import { shoppingOrders, getShopping, deletShop, Shopset } from "request";
import mixins from "mixins";
export default {
    mixins: [mixins],
    data() {
        return {
            checkall: false,
            bottomlist: [],
            route: {},
            shopNum: 0,
            shopprice: 0,
            shopIntergral: 0,
            shopType: "",
            freights: 0,
            startX: 0,
            endX: 0,
            checkallfalse: "",
            shopLists: []
        };
    },
    components: {
        XNumber
    },
    computed: {
        imgUrl() {
            return this.$store._modules.root._children.a.state;
        }
    },
    created() {
        // $router 直接监听无效，尚未查明，故作深拷贝处理
        this.route = Object.assign({}, this.$route);
        this.getShopdata();
        // this.clicks()
    },
    updated() {
        if (this.$refs.checkbox == undefined) {
        } else {
            for (var i = 0; i < this.$refs.checkbox.length; i++) {
                this.$refs.checkbox[i].addEventListener(
                    "click",
                    this.clicks,
                    false
                );
                this.$refs.number[i].addEventListener(
                    "click",
                    this.clicks,
                    false
                );
            }
        }
    },
    beforeDestroy() {
        document.removeEventListener("click", this.clicks, false);
    },
    methods: {
        //点击监听用户操作
        clicks(ev) {
            ev.stopPropagation();
            this.sTimeout();
        },
        allclicks() {
            this.sTimeout();
        },
        sTimeout() {
            setTimeout(() => {
                if (this.shopLists.length != 0) {
                    let allstr = [];
                    let allfalsenum = 0;
                    let alltruenum = 0;
                    this.shopprice = 0;
                    this.shopIntergral = 0;
                    for (var i = 0; i < this.shopLists.length; i++) {
                        if (this.shopLists[i].selectbox) {
                            this.shopprice += Number(
                                this.shopLists[i].buyNumber *
                                    this.shopLists[i].salePrice *
                                    100
                            );
                            this.shopIntergral +=
                                this.shopLists[i].integral *
                                this.shopLists[i].buyNumber;
                        }
                        allstr.push(String(this.shopLists[i].selectbox));
                    }
                    this.shopprice = (this.shopprice / 100).toFixed(2);
                    this.$store.commit("addShop", this.shopLists);
                    console.log(allstr)
                    for (var i in allstr) {
                        if (allstr[i].indexOf("false") > -1) {
                            allfalsenum++;
                        }
                        if (allstr[i].indexOf("true") > -1) {
                            alltruenum++;
                        }
                    }
                    //所有取消和所有选中 引发全部按钮
                    if (allfalsenum == this.shopLists.length) {
                        this.checkall = false;
                        this.checkallfalse = "all";
                    } else {
                        // this.checkall = false;
                        this.checkallfalse = "noall";
                    }
                    if (alltruenum == this.shopLists.length) {
                        this.checkall = true;
                    } else {
                    }
                } else {
                    this.checkall = false;
                    this.shopprice = 0;
                    this.shopIntergral = 0;
                }
            }, 100);
        },
        getShopdata() {
            this.$vux.loading.show({ text: "Loading" });
            getShopping({}).then(response => {
                if (response.rspCode == "0000") {
                    if (response.data.code == "0000") {
                        this.shopLists = response.data.productList;
                        this.shopLists.length == 0 && (this.showBg = true);
                        for (var i = 0; i < this.shopLists.length; i++) {
                            this.shopLists[i].selectbox =
                                this.shopLists[i].selectbox === "false" ? false : true;
                            this.shopLists[i].buyNumber = Number(
                                this.shopLists[i].buyNumber
                            );
                            this.shopprice += this.shopLists[i].buyNumber * this.shopLists[i].salePrice
                        }
                        // let is = this.shopLists.some(item=>{
                        //     return item.selectbox == false;
                        // })
                        // !is && (this.checkall = true);
                        // 图片加域名
                        for (var item of this.shopLists) {
                            item.picUrl = this.imgUrl + item.picUrl;
                        }
                    } else if (response.data.code == "7000") {
                        Toast({
                            message: "没有数据",
                            position: "bottom",
                            duration: 1000
                        });
                    }
                } else {
                    Toast({
                        message: "请求失败",
                        position: "bottom",
                        duration: 1000
                    });
                }
                this.$vux.loading.hide();
            }).catch(error => {
                console.log(error);
                this.$vux.loading.hide();
            });
        },
        change(item,type) {
            console.log(item.selectbox)
            this.counts = (this.counts || 0) + 1
            if(this.counts <= this.shopLists.length){
                return;
            }
            if (item.buyNumber > 50) {
                MessageBox("", "最多购买50份哟");
            }
            Shopset({
                isAdd: "02",
                productNo: item.productNo,
                specIds: item.specId,
                buynum: item.buyNumber,
                selectBox: `${ type ? !item.selectbox : item.selectbox}`
            }).then(response => {console.log(response)}).catch(error => { 
                console.log(error);
            });
        },
        //全选
        slect() {
            for (var i = 0; i < this.shopLists.length; i++) {
                this.shopLists[i].selectbox = true;
                this.change(this.shopLists[i]);
            }
            this.allclickcheck = "all";
            this.allclicks();
        },
        //取消全选
        canceLslect() {
            for (var i = 0; i < this.shopLists.length; i++) {
                this.shopLists[i].selectbox = false;
                this.change(this.shopLists[i]);
            }
            this.allclickcheck = "all";
            this.allclicks();
        },
        //结算
        async settlement() {
            let tyarr = "";
            var noselctarr = [];
            for (var i = 0; i < this.shopLists.length; i++) {
                if (this.shopLists[i].selectbox) {
                    //是否实物，地址显示
                    tyarr += this.shopLists[i].productType;
                } else if (!this.shopLists[i].selectbox) {
                    noselctarr.push(this.shopLists[i]);
                }
            }
            this.$store.commit("setno", noselctarr);
            //是否实物，地址显示
            if (tyarr.indexOf("1") > -1) {
                this.shopType = "1";
            } else {
                this.shopType = "3";
            }
            let totaljson = {
                shopType: this.shopType
            };
            let shoparr = [];
            for (var i = 0; i < this.shopLists.length; i++) {
                if (this.shopLists[i].selectbox) {
                    shoparr.push(this.shopLists[i]);
                }
            }
            console.log(shoparr);
            let goResultpage = true;
            // console.log(shoparr)
            if (shoparr.length == 0) {
                MessageBox("", "请选择商品");
                return false;
            }
            //计算运费，所选商品总额
            this.$vux.loading.show({
                text: "Loading"
            });
            await shoppingOrders({ productList: shoparr }).then(response => {
                    if (response.rspCode == "0000") {
                        if (response.data.resultCode == "00") {
                            let orderList = Object.assign({}, response.data);
                            totaljson.shopIntergral = orderList.totalIntegral;
                            totaljson.shopprice = orderList.totalAmount;
                            totaljson.freight = orderList.totalFreight;
                            totaljson.couponList = orderList.couponList;
                            totaljson.a = "orderList.couponList";
                            goResultpage = true;
                        } else {
                            MessageBox( "", response.data.resultMesg || "结算失败" );
                            goResultpage = false;
                        }
                    } else if (response.rspCode == "1999") {
                        MessageBox("", response.rspMsg || "结算失败");
                        this.$router.push({ path: "/" });
                    } else {
                        MessageBox("", "结算失败");
                        goResultpage = false;
                    }
                    this.$vux.loading.hide();
                }).catch(
                    error => console.log(error),
                    (goResultpage = false),
                    this.$vux.loading.hide()
                );
            //是否有库存，计算是否成功，发送选择商品和计算数据
            if (goResultpage) {
                this.$store.commit("addtotal", totaljson);
                this.$store.commit("slectShop", shoparr);
                if (shoparr.length < 1) {
                    MessageBox("", "请选择商品");
                } else {
                    this.$store.commit("setno", noselctarr);
                    this.$store.commit("mchtCouponList", totaljson.couponList);
                    this.$router.push({
                        path: "/shopResult"
                    });
                }
            }
        },
        deleteshop(item) {
            if (item.specId) {
                var jsonObj = {
                    type: "02",
                    specIdList: [item.specId],
                    productNoS: [item.productNo]
                };
            } else {
                var jsonObj = { type: "02", productNoS: [item.productNo] };
            }
            //  02 删除 01 购买
            deletShop(jsonObj)
                .then(response => {
                    console.log(response.rspCode);
                    if (response.rspCode == "0000") {
                        console.log(response.data.code);
                        if (response.data.code == "0000") {
                            Toast({
                                message: response.data.rspMsg || "操作成功",
                                position: "middle",
                                duration: 3000
                            });
                        } else {
                            MessageBox(
                                "",
                                response.data.resultMesg || "删除失败"
                            );
                        }
                    } else {
                        MessageBox("", "删除失败");
                    }
                })
                .catch(error => console.log(error));
        },

        //滑动开始
        touchStart(e) {
            // 记录初始位置
            this.startX = e.touches[0].clientX;
        },
        //滑动结束
        touchEnd(e) {
            // 当前滑动的父级元素
            let parentElement = e.currentTarget.parentElement;
            // 记录结束位置
            this.endX = e.changedTouches[0].clientX;

            // 左滑
            if (
                parentElement.dataset.type == 0 &&
                this.startX - this.endX > 30
            ) {
                this.restSlide();
                parentElement.dataset.type = 1;
            }
            // 右滑
            if (
                parentElement.dataset.type == 1 &&
                this.startX - this.endX < -30
            ) {
                this.restSlide();
                parentElement.dataset.type = 0;
            }
            this.startX = 0;
            this.endX = 0;
        },
        //判断当前是否有滑块处于滑动状态
        checkSlide() {
            let listItems = document.querySelectorAll(".listchild");
            for (let i = 0; i < listItems.length; i++) {
                if (listItems[i].dataset.type == 1) {
                    return true;
                }
            }
            return false;
        },
        //复位滑动状态
        restSlide() {
            let listItems = document.querySelectorAll(".listchild");
            // 复位
            for (let i = 0; i < listItems.length; i++) {
                listItems[i].dataset.type = 0;
            }
        },
        //删除
        deleteItem(ev, index, item) {
            this.deleteshop(item);
            ev.stopPropagation();
            // 复位
            this.restSlide();
            // 页面删除
            this.shopLists.splice(index, 1);
            //删除影响页面总金额的变化
            this.clicks();
            // 后台逻辑删除
        }
    },
    destroyed() {},
    watch: {
        checkall() {
            if (this.checkall) {
                this.slect();
            } else {
                this.canceLslect();
            }
        }
    }
};
</script>
<style lang="less" scoped>
@import "./../css/ckecked.css";
@import "./index.less"
</style>
 

